package com.example.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.example.hadoop.HDFS;


@Controller
public class UploadController{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private HDFS hdfs;
	
	@ResponseBody
	@RequestMapping("/upload/image")
	public JSONObject upload(@RequestParam MultipartFile file) throws IOException{
		JSONObject obj = new JSONObject();
		try {
			
			StringBuilder sb = new StringBuilder();
			sb.append("/pdf/");
			sb.append(file.getOriginalFilename());
			
			hdfs.create(file.getInputStream(), sb.toString());
			
			obj.put("code", "0");
			obj.put("msg", "上传成功");
			
			JSONObject o = new JSONObject();
			o.put("src", sb.toString());
			o.put("title",file.getOriginalFilename());
			obj.put("data", o);
			
		} catch (Exception e) {
			e.printStackTrace();
			obj.put("code", "-1");
			obj.put("msg", "上传失败");
			
			JSONObject o = new JSONObject();
			o.put("src", "");
			o.put("title",e.getMessage());
			obj.put("data", o);
		}
		
		logger.debug(obj.toString());
		
		return obj;
	}
	
	@RequestMapping("/displayPDF.do")
    public void displayPDF(HttpServletResponse response) {
        try {
        	InputStream input = hdfs.getFile("/compressed.tracemonkey-pldi-09.pdf");
            response.setHeader("Content-Disposition", "attachment;fileName=test.pdf");
            response.setContentType("multipart/form-data");
            OutputStream outputStream = response.getOutputStream();
            IOUtils.write(IOUtils.toByteArray(input), outputStream);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
	

}
